// utils/ws.js

import { WS_HEARTBEAT_URL } from './config'

let socket = null
let heartTimer = null
let reconnectTimer = null

const HEARTBEAT_INTERVAL = 30000  // 每 30 秒发送一次心跳
const RECONNECT_INTERVAL = 5000   // 断线重连时间

export function connectWebSocket(onMessageCallback) {
  if (socket) {
    console.log('WebSocket 已连接')
    return
  }

  socket = wx.connectSocket({
    url: WS_HEARTBEAT_URL,
    header: {
      'content-type': 'application/json',
    },
    success() {
      console.log('WebSocket 发起连接成功')
    },
    fail(err) {
      console.error('WebSocket 连接失败:', err)
    }
  })

  socket.onOpen(() => {
    console.log('✅ WebSocket 连接已打开')
    startHeartbeat()
  })

  socket.onMessage((res) => {
    console.log('📩 收到服务器消息:', res.data)
    if (typeof onMessageCallback === 'function') {
      onMessageCallback(res.data)
    }
  })

  socket.onClose(() => {
    console.warn('❌ WebSocket 连接关闭')
    clearHeartbeat()
    reconnect()
  })

  socket.onError((err) => {
    console.error('💥 WebSocket 错误:', err)
    reconnect()
  })
}

function startHeartbeat() {
  heartTimer = setInterval(() => {
    if (socket && socket.readyState === 1) {
      socket.send({
        data: 'ping',
        success() {
          console.log('🔄 心跳 ping 已发送')
        },
        fail(err) {
          console.warn('心跳发送失败:', err)
        }
      })
    }
  }, HEARTBEAT_INTERVAL)
}

function clearHeartbeat() {
  if (heartTimer) clearInterval(heartTimer)
}

function reconnect() {
  if (reconnectTimer) return
  reconnectTimer = setTimeout(() => {
    reconnectTimer = null
    console.log('🔁 正在尝试重连 WebSocket...')
    socket = null
    connectWebSocket()
  }, RECONNECT_INTERVAL)
}

export function closeWebSocket() {
  clearHeartbeat()
  if (socket) {
    socket.close()
    socket = null
  }
}
